<template>
  <div class="home">
    <div class="detail_box">
      <!-- 菜单 -->
      <div class="tab_menu">
        <div>
          <span v-for="(item,index) in menus" :class="{'choose':index===mIndex}" @click="chooseTab(index,item.id)"
                :key="index">{{ item.name }}订单</span>
        </div>
      </div>
      <!-- 操作 -->
      <div class="operate_box">
        <div class="item_box">

          <!-- 仓管和配送员不需仓库和配送员 -->
          <div class="operate_item" v-if="user&&user.type!==3&&user.type!==6">
            <label>仓库：</label>
            <el-select
              filterable
              @change="getSender"
              v-model="warehouseId"
              placeholder="请选择仓库">
              <el-option label="全部" :value="''" v-if="!roleHouse.id"></el-option>
              <el-option
                v-for="(item,index) in warehouseOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item" v-if="warehouseId&&user&&user.type!==3&&user.type!==6">
            <label>配送员：</label>
            <el-select
              filterable
              v-model="senderId"
              placeholder="请选择配送员" clearable>
              <el-option
                v-for="(item,index) in senderOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item">
            <label>预约单号：</label>
            <el-input type="text" placeholder="请输入预约单号" v-model="keyword" clearable></el-input>
          </div>
          <div class="operate_item" v-if="user&&user.type!==6&&!$route.query.userId">
            <label>用户：</label>
            <userSelect @listenToUser="getUserId" :uId="uId"/>
          </div>
          <div class="operate_item">
            <label>时间：</label>
            <el-date-picker
              v-model="proDate"
              type="datetimerange"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </div>
          <div class="operate_item">
            <span class="operate_btn search_btn" @click="searchData">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
        <div class="btn_box" v-if="btn&&btn.createOrder">
          <span class="operate_btn search_btn" @click="isCreate=true">下单</span>
        </div>
      </div>
      <!-- 表格 -->
      <div class="flex_box">
        <div class="detail_part" :class="{'left_box':isPop}">
          <div class="table_box">
            <el-table
              border
              v-loading="loading"
              :header-cell-style="tableHeader"
              ref="multipleTable"
              :data="tableInfo"
              tooltip-effect="dark"
              highlight-current-row
              style="width: 100%;"
              @sort-change="getChange"
            >
              <el-table-column
                width="160"
                sortable='custom'
                prop="1"
                label="创建时间"
              >
                <template slot-scope="scope">
                  <p style="text-align: left">{{ formatTime(scope.row.createTime) }}</p>
                </template>
              </el-table-column>

              <el-table-column
                width="160"
                prop="1"
                label="修改时间"
              >
                <template slot-scope="scope">
                  <p style="text-align: left">{{ formatTime(scope.row.modifyTime) }}</p>
                </template>
              </el-table-column>

              <el-table-column
                width="150"
                label="用户">
                <template slot-scope="scope">{{ scope.row.name ? scope.row.name : '——' }}</template>
              </el-table-column>

              <el-table-column
                width="100"
                prop="userId"
                label="用户ID">
              </el-table-column>

              <el-table-column
                width="230"
                prop="recordNo"
                label="订单号">
              </el-table-column>
              <el-table-column
                label="分配仓库">
                <template slot-scope="scope">{{ scope.row.warehouseName ? scope.row.warehouseName : '——' }}</template>
              </el-table-column>
              <el-table-column
                width="150"
                prop="4"
                label="配送员" sortable='custom'>
                <template slot-scope="scope">{{ scope.row.senderName ? scope.row.senderName : '——' }}</template>
              </el-table-column>
              <el-table-column
                width="140"
                label="配送员电话">
                <template slot-scope="scope">{{ scope.row.senderPhone ? scope.row.senderPhone : '——' }}</template>
              </el-table-column>
              <el-table-column
                width="110"
                prop="3"
                label="配送数量" sortable='custom'>
                <template slot-scope="scope">{{ scope.row.numbers ? scope.row.numbers : 0 }}</template>
              </el-table-column>
              <el-table-column
                width="250"
                label="配送地址">
                <template slot-scope="scope">{{ scope.row.address ? scope.row.address : '——' }}</template>
              </el-table-column>

              <el-table-column
                label="备注">
                <template slot-scope="scope">{{ scope.row.remark ? scope.row.remark : '——' }}</template>
              </el-table-column>

              <el-table-column
                width="80"
                label="状态"
                sortable='custom'
                prop="2"
              >
                <template slot-scope="scope">
                  <div
                    :style="'color:'+(scope.row.enable===1?'#67c430':(scope.row.enable===2||scope.row.enable===4||scope.row.enable===5||scope.row.enable===3?'orange':'#e40000'))">
                    {{ scope.row.enable === 1 ? '已完成' : (scope.row.enable === 2 ? '待分配' : (scope.row.enable === 3 ? '待确认' : (scope.row.enable === 4 ? '待出货' : (scope.row.enable === 5 ? '配送中' : '已取消')))) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                v-if="btn&&(btn.detail||btn.assignOrder||btn.confirmDelivery||btn.confirmSend||btn.cancel||btn.addOrder || btn.changeSend ||btn.queryShipment || btn.changeSender || btn.delay || btn.bindSender || btn.bindWarehouse)"
                width="220">
                <template slot-scope="scope">
                  <div class="table_btn">
                       <span class="change_info confirm_btn" @click="bindInfo(scope.row,1)"
                             v-if="btn.bindWarehouse">绑定仓库</span>
                       <span class="change_info confirm_btn" @click="bindInfo(scope.row,2)"
                             v-if="btn.bindSender">绑定配送员</span>
                    <span class="change_info" @click="openPopup(scope.row,1)" v-if="btn.detail">详情</span>
                    <span class="change_info" @click="openPopup(scope.row,2)"
                          v-if="btn.assignOrder&&(scope.row.enable!==6 && scope.row.enable!==1)">{{
                        scope.row.enable === 2 ? '分配配送员' : '更换配送员'
                      }}</span>
                    <span class="change_info" @click="openPopup(scope.row,2)"
                          v-if="btn.changeSender&&scope.row.enable===3&&user.type===6">换单</span>
                    <span class="change_info confirm_btn" @click="confirmOrder(scope.row)"
                          v-if="btn.confirmDelivery&&scope.row.enable===3">确认配送</span>
                    <span class="change_info finish_btn" @click="finishOrder(scope.row)"
                          v-if="btn.confirmSend&&scope.row.enable===5">确认送达</span>
                    <span class="change_info delete_btn" @click="openPopup(scope.row,4)"
                          v-if="(scope.row.enable===2)&&btn.changeSend">仓库转单</span>
                    <span class="change_info await" @click="openPopup(scope.row,5)"
                          v-if="(scope.row.enable===2)&&btn.addOrder">追加配送</span>
                    <span class="change_info" @click="goContact(scope.row)" v-if="btn.queryShipment">出货单</span>
                    <span class="change_info delete_btn" @click="openDelay(scope.row)"
                          v-if="scope.row.enable === 5 && btn.delay">延迟配送</span>
                    <span class="change_info delete_btn" @click="openPopup(scope.row,6)"
                          v-if="btn.cancel && (scope.row.enable !== 1 && scope.row.enable !== 6)">取消</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="record_page">
            <span class="page_count">共<i>{{ totals }}</i>条</span>
            <el-pagination
              @size-change="sizeChange"
              @current-change="getTableInfo"
              background
              :current-page="currentPage"
              :page-sizes="[15, 20, 30, 40]"
              :page-size="pageSize"
              layout="prev, pager, next, sizes,jumper"
              :total="totals">
            </el-pagination>
          </div>
        </div>
        <div class="right_box" v-if="isPop">
          <p class="page_title">{{ orderNo }}订单详情 <i class="detail_close" @click="closeDetail"></i> </p>
          <detail :userId="userId" :orderNo="orderNo"></detail>
          <p class="page_title">{{ orderNo }}订单日志 <i class="detail_close" @click="closeDetail"></i> </p>
          <log :userId="userId" :orderNo="orderNo"></log>
        </div>
      </div>

    </div>
    <createOrder v-if="isCreate" @listenToChild="listenToEdit"></createOrder>
    <assignOrder v-if="isAssign" :record-id="orderId" :recordNo="orderNo" :changeType="changeType" :warehouse-id="wId" @listenToChild="listenToEdit"></assignOrder>
    <cancelOrder v-if="isCancel" :record-id="orderNo" @listenToChild="listenToEdit"></cancelOrder>
    <delayOrder v-if="isDelay" :record-id="orderNo" @listenToChild="listenToEdit"></delayOrder>
    <return-pail v-if="isReturn" :order-id="orderId" :user-id="userId" @listenToChild="listenToEdit"></return-pail>
    <changeWarehouse v-if="isChange" :record-id="orderNo" @listenToChild="listenToEdit"></changeWarehouse>
    <addOrder v-if="isAdd" :record-id="orderNo" :warehouse-id="wId" @listenToChild="listenToEdit"></addOrder>
<!-- 地址绑定配送员-->
    <bindSender v-if="isBindSender" :warehouseId="orderInfo.warehouseId" :address="orderInfo.address" :addressId="orderInfo.addressId" @listenToChild="listenToEdit"></bindSender>
<!--    绑定仓库-->
    <BindWarehouse v-if="isBindWarehouse" :warehouseId="orderInfo.warehouseId" :address="orderInfo.address" :addressId="orderInfo.addressId" @listenToChild="listenToEdit"></BindWarehouse>

  </div>
</template>

<script>


import log from '../log/index'
import detail from '../detail/index'
import createOrder from "./createOrder";
import assignOrder from "./assignOrder";
import cancelOrder from "./cancelOrder";
import returnPail from "./returnPail";
import changeWarehouse from "./changeWarehouse";
import addOrder from "./addOrder"
import userSelect from '../../../components/user/index'
import delayOrder from "./delayOrder";
import bindSender from "./bindSender";
import commons from "@/utils/common";
import {cancelSend, confirmDelivery, confirmSend, listData} from "@/api/data/user/productSend";
import {getAllWarehouse} from "@/api/basic/warehouse";
import {getAllData} from "@/api/basic/warehouse/sender";
import {getBtn} from "@/utils/btnAuth";
import {getReturnProduct} from "@/api/data/user/product";
import {judgeRole} from "@/utils/warehouseAuth";
import {formatTree} from "@/utils/menuAuth";
import BindWarehouse from "./bindWarehouse";

export default {
  components: {
    BindWarehouse,
    log,
    detail,
    createOrder,
    assignOrder,
    returnPail,
    changeWarehouse,
    addOrder,
    userSelect,
    cancelOrder,
    delayOrder,
    bindSender,
    orderInfo:{}
  },
  data() {
    return {
      menus: [{name: '待处理', id: 2}, {name: '配送中', id: -2}, {name: '已完成', id: -3}],
      status: 2,
      mIndex: 0,
      proDate: '',
      keyword: '',
      uId: '',
      senderId: '',
      senderOption: [],
      warehouseId: '',
      warehouseOption: [],
      currentPage: 1,
      pageSize: 15,
      totals: 0,
      loading: false,
      tableInfo: [],
      isPop: false,
      userId: '',
      orderNo: '',
      isCreate: false,
      orderId: '',
      wId: '',
      isAssign: false,
      isReturn: false,
      isChange: false,
      isAdd: false,
      btn: {},
      sortNumber: '',
      roleHouse: {},
      user: {},
      deliveryNo: '',
      countDown: null,
      isCancel:false,
      recordId:'',
      isDelay:false,
      changeType:'',
      isBindSender:false,
      isBindWarehouse:false
    }
  },
  mounted() {
    let that = this;
    that.roleHouse = judgeRole();
    that.warehouseOption = that.roleHouse.list;
    that.warehouseId = that.roleHouse.id;
    if (that.warehouseId) {
      this.getSender(that.warehouseId)
    }
    let str = window.localStorage.getItem('water_user');
    if (str) {
      that.user = JSON.parse(str).loginUser;
    }

    if (that.$route.query.deliveryNo) {
      that.deliveryNo = that.$route.query.deliveryNo;
    }
    that.btn = getBtn();
    if (that.btn.query) {
      that.chooseTab(0,2);
    }
  },
  methods: {
    chooseTab(index, enable) {
      let that = this;
      that.isPop = false;
      that.mIndex = index;
      that.status = enable;
      that.getTableInfo(1);
      if (that.countDown){
        clearInterval(that.countDown);
        that.countDown = null;
      }
      if (that.mIndex===0){
        that.countDown = setInterval(function () {
          that.getTableInfo(that.currentPage);
        }, 90000)
      }
    },
    //关闭详情和日志
    closeDetail() {
      this.isPop = false;
    },
  //配送中订单可延迟配送
    openDelay(obj) {
      this.orderNo = obj.recordNo;
      this.isDelay = true;
    },
    //监听列表排序
    getChange(val) {
      let sort = parseInt(val.prop)
      if (this.sortNumber < 0) {
        this.sortNumber = sort;
        this.getTableInfo(1);
      } else {
        this.sortNumber = -sort;
        this.getTableInfo(1);
      }
    },

    //跳转出货单
    goContact(obj) {
      let that = this;
      let url = '/warehouse/shipment';
      let parent = '仓库管理';
      that.$router.push({
        path: url,
        query: {
          key: formatTree(parent, url),
          cId: obj.recordNo,
          username: obj.recordNo,
        }
      })
    },
    //绑定配送员
    bindInfo(obj,type) {
      this.orderInfo = obj;
      type === 1 ? this.isBindWarehouse = true : this.isBindSender = true
    },
    // 获取列表信息
    getTableInfo(page) {
      let that = this;
      that.loading = true;
      that.currentPage = page;
      let queryParams = {
        limit: that.pageSize,
        page: page,
        keyword: that.keyword,
        userId: that.$route.query.userId ? parseInt(this.$route.query.userId) : that.uId,
        warehouseId: that.warehouseId,
        senderId: that.senderId,
        sort: that.sortNumber,
        enable: that.status,
        deliveryNo: that.deliveryNo,
        startDate: that.proDate ? that.proDate[0] : '',
        endDate: that.proDate ? that.proDate[1] : '',
      }
      listData(queryParams).then(res => {
        that.tableInfo = res ? res.list : [];
        that.totals = res ? res.count : 0;
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },

    searchData() {
      this.isPop = false;
      this.getTableInfo(1)
    },

    // 重置
    resetTable() {
      this.pageSize = 15;
      this.keyword = '';
      this.uId = '';
      this.proDate = '';
      this.warehouseId = this.user && this.user.type !== 3 && this.user.type !== 6 ? '' : this.roleHouse.id;
      this.senderId = '';
      this.sortNumber = '';
      this.searchData();
    },

    // 获取用户
    getUserId(e) {
      this.uId = e;
    },

    // 获取仓库
    getWarehouse() {
      let that = this;
      getAllWarehouse('').then(res => {
        that.warehouseOption = res ? res : [];
      }).catch((e) => {
        that.warehouseOption = [];
      })
    },

    // 获取配送员
    getSender(val) {
      if (val) {
        let that = this;
        let params = {
          warehouseId: val,
          isAll:1
        }
        getAllData(params).then(res => {
          that.senderOption = res ? res : [];
        }).catch((e) => {
          that.senderOption = [];
        })
      }
    },

    // 确认配送订单
    confirmOrder(obj) {
      let that = this;
      that.$confirm('确定配送该订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return confirmSend({recordIds: obj.id, senderId: obj.senderId});
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success({
          message: '操作成功！',
          duration: 1500
        });
      }).catch(() => {
      });
    },

    // 确认送达
    finishOrder(obj) {
      let that = this;
      getReturnProduct({userId: obj.userId}).then((res) => {
        if (res) {
          that.openPopup(obj, 3);
        } else {
          that.$confirm('确定单号' + obj.recordNo + '的订单已经送达?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.confirmFinish(obj);
          }).catch(() => {
          });
        }
      })
    },

    confirmFinish(obj) {
      this.loading = true;
      let param = {
        id: obj.id,
      }
      confirmDelivery(param).then(res => {
        this.$message.success({
          message: '操作成功',
          duration: 1500
        });
        this.closePopup(true);
        this.getTableInfo(this.currentPage);
        this.loading = false;
      }).catch((e) => {
        this.loading = false;
      })
    },

    // 取消订单
    cancelOrder(obj) {
      this.$confirm('确定取消单号为' + obj.recordNo + '的订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelSend(obj.recordNo).then((res) => {
          if (res) {
            this.$message.success({
              message: '操作成功！',
              duration: 1500
            });
            this.getTableInfo(this.currentPage);
          }
        });
      }).catch(() => {
      });
    },

    // 打开弹窗
    openPopup(obj, type) {
      type === 1 ? this.isPop = true : (type === 2 ? this.isAssign = true : (type === 3 ? this.isReturn = true : (type === 4 ? this.isChange = true : (type === 5 ? this.isAdd = true : this.isCancel = true))));
      //更换配送员调用不同接口
      this.changeType = obj.enable;
      this.userId = obj.userId;
      this.orderId = obj.id;
      this.orderNo = obj.recordNo;
      this.wId = obj.warehouseId;
    },

    listenToEdit(e) {
      this.isCreate = false;
      this.isAssign = false;
      this.isReturn = false;
      this.isChange = false;
      this.isAdd = false;
      this.isDelay = false;
      this.isCancel = false;
      this.isBindSender = false;
      this.isBindWarehouse = false;
      if (e.refresh) {
        this.getTableInfo(this.currentPage)
      }
    },

    formatTime(time) {
      return commons.formatTime(time)
    },

    sizeChange(val) {
      this.pageSize = val;
      this.getTableInfo(1)
    },

    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
    },
  },
  beforeDestroy() {
    let that = this;
    clearInterval(that.countDown);
    that.countDown = null;
  },
  watch: {
    warehouseId(oldW, newW) {
      //根据当前仓库的变化,重置配送员,不然会出现下拉框值为数字
      this.senderId = '';
    }
  }
}
</script>

<style scoped>
.flex_box {
  display: flex;
}

.detail_part {
  width: 100%;
}

.left_box {
  width: 60%;
}

.right_box {
  width: 40%;
}

.page_title {
  font-weight: 600;
  padding-left: 20px;
  margin-bottom: 10px;
  font-size: 18px;
  position: relative;
}

.confirm_btn {
  color: #f7ab20;
}

.finish_btn {
  color: rgb(103, 196, 48);
}


</style>
